package com.bw.paper.mvp.view.news;

import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bw.paper.App;
import com.bw.paper.R;
import com.bw.paper.mvp.base.model.BaseEntity;
import com.bw.paper.mvp.base.view.BaseActivity;
import com.bw.paper.mvp.contract.LREContract;
import com.bw.paper.mvp.di.DaggerLREComponent;
import com.bw.paper.mvp.di.LREModules;
import com.bw.paper.mvp.model.HttpCode;
import com.bw.paper.mvp.model.entity.CommentEntity;
import com.bw.paper.mvp.model.entity.UserEntity;
import com.bw.paper.mvp.presenter.LREPresenter;
import com.bw.paper.mvp.view.news.adapter.CommentAdapter;
import com.bw.paper.utils.LogUtils;
import com.bw.paper.utils.ToastUtils;
import com.bw.paper.widget.x5.X5WebView;
import com.google.android.material.appbar.AppBarLayout;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class NewsValuesActivity extends BaseActivity<LREPresenter>
        implements LREContract.ILREView,View.OnClickListener,
        FaceFragment.OnEmojiClickListener, AppBarLayout.OnOffsetChangedListener {

    private ImageView head_back_img;
    private AppBarLayout web_values_appbar;
    private TextView live_msg_num_tv;
    private RelativeLayout live_msg_relative;
    private X5WebView web_values_x5;
    private RecyclerView web_values_comment_rv;
    private RelativeLayout live_edt_btn;//开启输入框
    private ImageView live_face_img;//显示表情包
    private ImageView live_emoji_img;//输入系统显示表情
    private RelativeLayout live_bottom_view;//输入系统整体布局
    private LinearLayout live_emoji_linear;//表情系统布局
    private EditText live_msg_edt;
    private TextView live_send_tv;//发送按钮
    private View headView;
    private CommentAdapter commentAdapter;
    private long news_id = 0;
    private String news_url;
    private boolean appFlag = true;//当前界面中appbarlayout展开以及折叠标志,fasle折叠true展开

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.live_edt_btn == id){
            live_bottom_view.setVisibility(View.VISIBLE);
            live_emoji_linear.setVisibility(View.GONE);
        }else if (R.id.live_face_img == id){
            live_bottom_view.setVisibility(View.VISIBLE);
            live_emoji_linear.setVisibility(View.VISIBLE);
        }else if (R.id.live_emoji_img == id){
            if (live_emoji_linear.getVisibility() == View.VISIBLE){
                //当前正在显示表情系统->隐藏掉表情布局
                live_emoji_linear.setVisibility(View.GONE);
                live_emoji_img.setImageResource(R.drawable.res_7icon_129);
            }else {
                //当前正在隐藏表情系统->显示表情布局
                live_emoji_linear.setVisibility(View.VISIBLE);
                live_emoji_img.setImageResource(R.drawable.res_7icon_131);
            }
        }else if (R.id.live_send_tv == id){
            if (live_msg_edt.getText() == null){
                ToastUtils.showMsg("请输入评论内容");
                return;
            }
            if (live_msg_edt.getText().toString().isEmpty()){
                ToastUtils.showMsg("请输入评论内容");
                return;
            }
            UserEntity entity = App.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                    .list().get(0);
            Map<String,Object>map = new HashMap<>();
            map.put("code",HttpCode.ADDCOMMENTCODE);
            map.put("comment_address","天津");
            map.put("comment_time",System.currentTimeMillis()/1000);
            map.put("comment_value",live_msg_edt.getText().toString());
            map.put("news_id",news_id);
            map.put("user_id",entity.user_id);
            //发布评论
            p.requestAll(map);

        }else if (R.id.head_back_img == id){
            finish();
        }else if (R.id.live_msg_relative == id){
            if (appFlag){
                live_msg_num_tv.setText("正文");
            }else {
                live_msg_num_tv.setText(""+937);
            }
            appFlag = !appFlag;
            web_values_appbar.setExpanded(appFlag);
        }
    }

    @Override
    public View addStatusView() {
        return f(R.id.web_values_root);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_web_values;
    }

    @Override
    public void initView() {
        headView = LayoutInflater.from(this).inflate(R.layout.view_web_values,null);
        news_url = getIntent().getExtras().getString("news_url");
        news_id = getIntent().getExtras().getLong("news_id",0);
        web_values_appbar = f(R.id.web_values_appbar);
        live_msg_relative = f(R.id.live_msg_relative);
        live_msg_num_tv = f(R.id.live_msg_num_tv);
        head_back_img = f(R.id.head_back_img);
        web_values_x5 = f(R.id.web_values_x5);
        live_edt_btn = f(R.id.live_edt_btn);
        live_face_img = f(R.id.live_face_img);
        live_bottom_view = f(R.id.live_bottom_view);
        live_emoji_linear = f(R.id.live_emoji_linear);
        live_emoji_img = f(R.id.live_emoji_img);
        live_send_tv = f(R.id.live_send_tv);
        live_msg_edt = f(R.id.live_msg_edt);
        web_values_comment_rv = f(R.id.web_values_comment_rv);
        web_values_x5.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                if (!s.contentEquals("http://118.195.161.134:8066/"))
                    return true;
                return false;
            }
        });
        getSupportFragmentManager().beginTransaction().add(R.id.live_emoji_linear,
                FaceFragment.Instance()).commit();
        web_values_x5.loadUrl(news_url);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        web_values_comment_rv.setLayoutManager(manager);
        commentAdapter = new CommentAdapter();
        commentAdapter.setEmptyView(R.layout.view_empty);
        commentAdapter.addHeaderView(headView);
        web_values_comment_rv.setAdapter(commentAdapter);
        live_edt_btn.setOnClickListener(this::onClick);
        live_face_img.setOnClickListener(this::onClick);
        live_emoji_img.setOnClickListener(this::onClick);
        live_send_tv.setOnClickListener(this::onClick);
        head_back_img.setOnClickListener(this::onClick);
        live_msg_relative.setOnClickListener(this::onClick);
        web_values_appbar.addOnOffsetChangedListener(this);
    }

    @Override
    public void initData() {
        Map<String ,Object>map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id",news_id);
        p.requestAll(map);
    }

    @Override
    public void inject() {
        DaggerLREComponent.builder().lREModules(new LREModules(this))
                .build().injectNewsValuesActivity(this);
    }

    @Override
    public void refreshAll(BaseEntity entity) {
        if (entity instanceof CommentEntity){
            CommentEntity commentEntity = (CommentEntity) entity;
            commentAdapter.setNewInstance(commentEntity.getValues());
        }else {
            if (entity.message.equals("发表成功")){
                //当前评论发布成功
                //清空输入框
                live_msg_edt.setText("");
                //刷新评论列表数据
                //请求获取最新评论列表
//                initData();
            }
        }
    }

    @Override
    public void refreshRecyckerView(BaseEntity entity) {

    }

    @Override
    public void loadMoreRecyclerView(BaseEntity entity) {

    }

    @Override
    public void onEmojiDelete() {
        String text = live_msg_edt.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                live_msg_edt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                try {
                    EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            live_msg_edt.getText().delete(index, text.length());
            try {
                EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        live_msg_edt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        try {
            EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (live_bottom_view.getVisibility() == View.VISIBLE){
                live_bottom_view.setVisibility(View.GONE);
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = live_msg_edt.getSelectionStart();
            Editable editable = live_msg_edt.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
            try {
                EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private int oldverticalOffset;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//        LogUtils.show("onOffsetChanged:"+verticalOffset);
        if (oldverticalOffset==verticalOffset)
            return;
        if (verticalOffset==0){
            //当前显示正文
            appFlag = true;
            live_msg_num_tv.setText(""+937);
        }else {
            appFlag = false;
            live_msg_num_tv.setText("正文");
        }
        oldverticalOffset = verticalOffset;
    }
}
